package com.ldatum.crm.daoImpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.ldatum.crm.dao.ContactsDao;
import com.ldatum.crm.domain.Contacts;
import com.ldatum.crm.util.HibernateUtil;

public class ContactsDaoImpl implements ContactsDao {

	@Override
	public void add(Contacts contacts) throws Exception {
		HibernateUtil.add(contacts);
	}

	@Override
	public void delete(Contacts contacts, int id) throws Exception {
		HibernateUtil.delete(contacts);
	}

	@Override
	public void update(Contacts contacts, int id) throws Exception {
		HibernateUtil.update(contacts);
	}

	@Override
	public Contacts findById(Class<Contacts> clazz, int id) throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			Contacts contacts = (Contacts) s.get(clazz, id);
			return contacts;
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public List<Contacts> list(Class<Contacts> clazz) throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			Criteria c  = s.createCriteria(clazz);
			@SuppressWarnings("unchecked")
			List<Contacts> list = (List<Contacts>) c.list();
			return list;
		}finally{
			s.close();
		}
	}

	@Override
	public Contacts findNameByNo(String no) throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			Criteria c  = s.createCriteria(Contacts.class);
			c.add(Restrictions.eq("cus_no", no));
			c.add(Restrictions.eq("type", "Importance"));
			@SuppressWarnings("unchecked")
			List<Contacts> contacts = (List<Contacts>) c.list();
			if(contacts==null){
				return new Contacts();
			}else{
				return contacts.get(0);
			}
			
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public List<Contacts> findByNo(Class<Contacts> clazz, String no) throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			Criteria c  = s.createCriteria(Contacts.class);
			c.add(Restrictions.eq("cus_no", no));
			@SuppressWarnings("unchecked")
			List<Contacts> list = (List<Contacts>) c.list();
			return list;
		}finally{
			if(s!=null)
			s.close();
		}
	}

	
}
